package com.hujf.netty.example.handle;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

import java.util.concurrent.TimeUnit;


/**
 * @author Hujf
 * @title: SimpleHandle
 * @date 2021/1/28 0028下午 12:57
 * @description: 实际业务处理类  自定义一个handle 首先集成netty的handle
 */
public class SimpleHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }

    //读取数据  接收客户端信息
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {


        //出现一个耗时任务
//        TimeUnit.SECONDS.sleep(10);
//        ctx.writeAndFlush(Unpooled.copiedBuffer("hello！ 好不容易我完成了",CharsetUtil.UTF_8));
//        System.out.println("响应成功");
//
        //异步解决耗时任务
        ctx.channel().eventLoop().execute(new Runnable() {
            @Override
            public void run() {
                try {
                    TimeUnit.SECONDS.sleep(10);
                    //ctx.writeAndFlush(Unpooled.copiedBuffer("hello！ 好不容易我完成了",CharsetUtil.UTF_8));
                    System.out.println("rw wanc ");
                }catch (Exception e){
                    System.out.println(e);
                }

            }
        });

        //用户自定义定时任务
        ctx.channel().eventLoop().schedule(new Runnable() {
            @Override
            public void run() {
                try {
                    TimeUnit.SECONDS.sleep(10);
                    //ctx.writeAndFlush(Unpooled.copiedBuffer("hello！ 好不容易我完成了",CharsetUtil.UTF_8));
                    System.out.println("rw wanc ");
                }catch (Exception e){
                    System.out.println(e);
                }

            }
        },5,TimeUnit.SECONDS);

        ctx.writeAndFlush(Unpooled.copiedBuffer("hello！ 好不容易我完成了",CharsetUtil.UTF_8));
        System.out.println("响应成功");



//        //super.channelRead(ctx, msg);
//        System.out.println(Thread.currentThread().getName()+" "+ctx);
//        //msg转出byte  ByteBuf 和ByteBuffer
//        ByteBuf buf = (ByteBuf) msg;
//        System.out.println(buf.toString(CharsetUtil.UTF_8)+" "+ctx.channel().remoteAddress());

    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.writeAndFlush(Unpooled.copiedBuffer("你个栽种",CharsetUtil.UTF_8));
    }


}
